package com.sunyur.tailor.channel.service.inner.settle.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.sunyur.tailor.channel.common.inner.base.SunyurListResult;
import com.sunyur.tailor.channel.common.inner.base.SunyurResult;
import com.sunyur.tailor.channel.common.inner.util.SunyurClientUtil;
import com.sunyur.tailor.channel.common.inner.util.SunyurResultUtil;
import com.sunyur.tailor.channel.common.middle.base.ChannelListResult;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.ChannelListResultUtil;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import com.sunyur.tailor.channel.service.inner.settle.model.SettleItemModel;
import com.sunyur.tailor.channel.service.inner.settle.model.SettleOrderItemModel;
import com.sunyur.tailor.channel.service.inner.settle.param.SettleItemCreateParam;
import com.sunyur.tailor.channel.service.inner.settle.param.SettleItemParam;
import com.sunyur.tailor.channel.service.inner.settle.param.SettleOrderItemParam;
import com.sunyur.tailor.channel.service.inner.settle.service.SunyurSettleOrderInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Author: HuBaoding
 * @Description: 流水信息 相关service
 * @Date: Created in 16:25 2021/5/17
 */
@Service("settleOrderInfoService")
public class SunyurSettleOrderInfoServiceImpl implements SunyurSettleOrderInfoService {

    private static final Logger LOGGER_INFO = LoggerFactory.getLogger(SunyurSettleOrderInfoServiceImpl.class);
    private static final Logger LOGGER_ERROR = LoggerFactory.getLogger(SunyurSettleOrderInfoServiceImpl.class);

    /**
     * 请求商越Client
     */
    @Autowired
    private SunyurClientUtil sunyurClient;

    @Value("${sunyur.api.listSettleOrderItemByCodes}")
    private String listSettleOrderItemByCodes;

    @Value("${sunyur.api.settleItem}")
    private String settleItem;

    @Value("${sunyur.api.settleItemCreate}")
    private String settleItemCreate;

    /**
     * 根据指定流水号，返回符合条件的应付流水列表结果
     *
     * @param param
     * @return
     */
    @Override
    public ChannelListResult<SettleOrderItemModel> listSettleOrderItemByCodes(SettleOrderItemParam param) {
        List<SettleOrderItemModel> resultList = Lists.newArrayList();
        try {
            List<String> settleOrderItemCodes = param.getSettleOrderItemCodes();
            List<List<String>> partition = Lists.partition(settleOrderItemCodes, 100);
            // 错误信息List
            List<String> errorMsgList = Lists.newArrayList();
            SettleOrderItemParam settleOrderItemParam = new SettleOrderItemParam();
            TypeReference<SunyurListResult<SettleOrderItemModel>> typeReference = new TypeReference<SunyurListResult<SettleOrderItemModel>>() {
            };
            for (List<String> codes : partition) {
                settleOrderItemParam.setSettleOrderItemCodes(codes);
                // 调用主线接口
                SunyurListResult<SettleOrderItemModel> sunyurListResult = sunyurClient.execListPost(listSettleOrderItemByCodes, JSON.toJSONString(settleOrderItemParam), typeReference);
                if (SunyurResultUtil.isSuccess(sunyurListResult)) {
                    resultList.addAll(sunyurListResult.getContent());
                } else {
                    LOGGER_ERROR.error("SunyurSettleOrderInfoServiceImpl listSettleOrderItemByCodes, param is {}, result is {}", JSON.toJSONString(settleOrderItemParam), JSON.toJSONString(sunyurListResult));
                    // 每批次错误信息收集
                    errorMsgList.add(sunyurListResult.getContent() + "-" + sunyurListResult.getErrorMessage());
                }
            }
            // 存在错误信息
            if (!CollectionUtils.isEmpty(errorMsgList)) {
                return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
            }
            return ChannelListResultUtil.success(resultList);
        } catch (Exception e) {
            LOGGER_ERROR.error("SettleOrderInfoServiceImpl listSettleOrderItemByCodes fail,param is {} ", JSON.toJSONString(param));
            return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), e.getMessage());
        }
    }

    @Override
    public ChannelListResult<SettleItemModel> settleItem(SettleItemParam param) {
        SunyurListResult<SettleItemModel> sunyurResult;
        try {
            sunyurResult = sunyurClient.execListPost(settleItem, JSON.toJSONString(param), new TypeReference<SunyurListResult<SettleOrderItemModel>>() {
            });
            // 主线返回错误
            if (!SunyurResultUtil.isSuccess(sunyurResult)) {
                return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurResult.getErrorMessage());
            }
        } catch (Exception e) {
            LOGGER_ERROR.error("SettleOrderInfoServiceImpl settleItem fail,param is {} ", JSON.toJSONString(param));
            return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), e.getMessage());
        }
        LOGGER_INFO.info("SettleOrderInfoServiceImpl settleItem param is {} , result is {}", JSON.toJSONString(param), JSON.toJSONString(sunyurResult));
        return ChannelListResultUtil.success(sunyurResult.getContent());
    }

    @Override
    public ChannelResult<Boolean> create(SettleItemCreateParam param) {
        SunyurResult sunyurResult;
        try {
            sunyurResult = sunyurClient.execPost(settleItemCreate, JSON.toJSONString(param), null);
            // 主线返回错误
            if (!SunyurResultUtil.isSuccess(sunyurResult)) {
                return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurResult.getErrorMessage());
            }
        } catch (Exception e) {
            LOGGER_ERROR.error("SettleOrderInfoServiceImpl settleItem fail,param is {} ", JSON.toJSONString(param));
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), e.getMessage());
        }
        LOGGER_INFO.info("SettleOrderInfoServiceImpl settleItem param is {} , result is {}", JSON.toJSONString(param), JSON.toJSONString(sunyurResult));
        return ChannelResultUtil.success(true);
    }
}
